<?php

namespace App\Admin\Controllers\Vote\Chapter;

use App\Admin\Actions\Batches\BatchDisable;
use App\Admin\Actions\Batches\BatchEnable;
use App\Admin\Actions\GoBackButton;
use App\Admin\Traits\WithUploads;
use App\Models\Chapter;
use App\Models\Gift;
use App\Models\Sponsor;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Illuminate\Http\JsonResponse;
use Illuminate\Routing\Controller;

class SponsorController extends Controller
{
    use WithUploads;

    public function index(Content $content, Chapter $chapter): Content
    {
        return $content->header('赞助商列表')
            ->description($chapter->title)
            ->body($this->grid($chapter));
    }

    public function grid(Chapter $chapter): Grid
    {
        $model = Sponsor::ofAdmin()
            ->where('chapter_id', $chapter->getKey())
            ->with(['chapter'])
            ->ordered();

        return Grid::make($model, function (Grid $grid) {
            $grid->batchActions([
                new BatchEnable(Gift::class),
                new BatchDisable(Gift::class),
            ]);
            $grid->tools([new GoBackButton()]);
            $grid->column('name');
            $grid->column('cover')
                ->thumb();
            $grid->column('order')
                ->orderable();
            $grid->column('status')
                ->bool();
            $grid->column('created_at');
        });
    }

    public function create(Content $content, Chapter $chapter): Content
    {
        return $content->header('新增赞助商')
            ->description($chapter->title)
            ->body($this->form($chapter));
    }

    public function form(Chapter $chapter): Form
    {
        return Form::make(Sponsor::ofAdmin(), function (Form $form) use ($chapter) {
            $form->hidden('chapter_id')
                ->value($chapter->getKey());

            $form->text('name')
                ->required();
            $this->cover($form)
                ->dimensions(['min_width' => 100, 'max_width' => 200])
                ->help('图片宽度请在100~200px之间')
                ->required()
                ->width(5);
            $form->url('url', '跳转地址')
                ->help('如果没有则留空');
        });
    }

    public function edit(Content $content, Chapter $chapter, int $id): Content
    {
        return $content->header('编辑赞助商')
            ->description($chapter->title)
            ->body($this->form($chapter)->edit($id));
    }

    public function update(Chapter $chapter, int|string $id): JsonResponse
    {
        return $this->form($chapter)->update($id);
    }

    public function store(Chapter $chapter): JsonResponse
    {
        return $this->form($chapter)->store();
    }

    public function destroy(Chapter $chapter, int|string $id): JsonResponse
    {
        return $this->form($chapter)->destroy($id);
    }
}
